package util;

import com.fasterxml.jackson.databind.ObjectMapper;
import dto.LayResultDTO;
import dto.ResultDTO;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class Result {


    /**
     * 响应json数据 - 返回数据
     * @param response
     * @param data
     */
    public static void response(Integer code, String msg, HttpServletResponse response, Object data){
        try {
            // 构建结果传输对象
            ResultDTO resultDto = new ResultDTO(code, msg, data);
            // 将对象转换成json
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonData = objectMapper.writeValueAsString(resultDto);
            // 设置响应头
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonData);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 响应给layui的数据
     * @param code
     * @param msg
     * @param count
     * @param response
     * @param data
     */
    public static void response(Integer code, String msg, Integer count,  HttpServletResponse response, Object data){
        try {
            // 构建结果传输对象
            ResultDTO resultDto = new LayResultDTO(code, msg, count, data);
            // 将对象转换成json
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonData = objectMapper.writeValueAsString(resultDto);
            // 设置响应头
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonData);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 响应json数据 - 不返回数据
     * @param response
     */
    public static void response(Integer code, String msg, HttpServletResponse response){
        try {
            // 构建结果传输对象
            ResultDTO resultDto = new ResultDTO(code, msg);
            // 将对象转换成json
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonData = objectMapper.writeValueAsString(resultDto);
            // 设置响应头
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonData);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
